<template>
    <el-dialog v-model="dialogFormVisible" title="代码生成配置">
        <el-form :model="form" label-width="auto" :rules="rules" ref="ruleFormRef">
            <el-form-item label="包名" prop="packageName">
                <el-input clearable v-model="form.packageName" placeholder="请输入包名" />
            </el-form-item>
            <el-form-item label="模块名" prop="moduleName">
                <el-input clearable v-model="form.moduleName" placeholder="请输入模块名" />
            </el-form-item>
            <el-form-item label="表前缀" prop="tablePrefix">
                <el-input clearable v-model="form.tablePrefix" placeholder="请输入需要忽略的表前缀" />
            </el-form-item>
            <el-form-item label="开发者">
                <el-input clearable v-model="form.author" placeholder="请输入开发者" />
            </el-form-item>
            <el-form-item label="邮箱">
                <el-input clearable v-model="form.email" placeholder="请输入开发者邮箱" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">返回</el-button>
                <el-button type="primary" @click="generateCode">确认</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup name="addEdit">
import { ref } from "vue";
import api from "@/api"
import { ElMessage } from 'element-plus'

const ruleFormRef = ref()
const dialogFormVisible = ref(false)
const form = ref({ packageName: 'com.blue' })
const rules = ref({
    packageName: [
        { required: true, message: '请输入包名', trigger: 'blur' },
    ],
    moduleName: [
        { required: true, message: '请输入模块名', trigger: 'blur' },
    ],
    tablePrefix: [
        { required: true, message: '请输入表前缀', trigger: 'blur' },
    ]
})

const init = async (tableNms) => {
    form.value.tableNames = tableNms
    dialogFormVisible.value = true
}
const generateCode = () => {
    ruleFormRef.value.validate(async (valid) => {
        if (valid) {
            const res = await api.post('/system/generate/generateCode', form.value, 'blob')
            const data = res.data
            const blob = new Blob([data], {
                type: 'application/zip;charset=UTF-8'
            })
            const url = URL.createObjectURL(blob)
            const a = document.createElement('a')
            a.href = url
            a.download = 'blue'
            a.click()
            form.value = { packageName: 'com.blue' }
            ElMessage.success('代码已生成！')
            dialogFormVisible.value = false
        }
    })
}

defineExpose({
    init
});
</script>